const path = require('path');
const router = require('koa-router')();
const model = require('../../models/user');
const timestring = require('../../utils/lib/time').timestring;
const { v4: uuidv4} = require('uuid');
const bodyparser = require('koa-bodyparser');
const { redis } = require('../../config/env');
const RedisStore = require('koa-redis')(redis);

const Koa = require("koa");
const app = new Koa();

app.use(bodyparser());
const dao = require('../../dao/' + path.basename(__dirname));



router.post('/v1/user/login', async function (ctx, next) {
    let { account, password } = ctx.request.body;           //获取表单登录用户名与密码
    let middle = await model.findOne({
        where: {
            username: account,
        }
    });
    let _user = JSON.stringify(middle);
    let user = JSON.parse(_user);       //结果json对象化
    if (user && (user.password === password)) {
        ctx.session['userAccount'] = user.username;
        ctx.session['logged'] = true;
        let session_id = uuidv4(user.id);
        let session_is_exist = await RedisStore.get(session_id);        //判断是否有相同session_id存在
        if (session_is_exist) {
            await RedisStore.destroy(session_id);
        }
        const result0 = await RedisStore.set(session_id, ctx.session, 24 * 60 * 60 * 1000);
        console.log('登录成功!');
        let time = timestring();
        dao.update({ last_login_at: time, session_id: session_id }, {            //记录最近登录时间
            username: account
        });
        ctx.cookies.set('session_id', uuidv4(user.id), {
            maxAge: 24 * 60 * 60 * 1000,
        })
        ctx.session.logged = true;
        ctx.response.status = 200;
        ctx.type = 'json/application';
        ctx.response.body = {
            'statusCode': 200,
            'user': user,
        };       //将全部用户信息返回
    } else if (user && (user.password !== password)) {          //密码错误
        console.log('密码错误');
        console.log(user);
        console.log(password);
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: "密码错误!"
        }
    } else if (!user) {             //用户名不存在
        console.log('用户名不存在!');
        console.log(user);
        console.log(password);
        ctx.response.status = 500;
        ctx.type = 'json/application';
        ctx.response.body = {
            code: 500,
            ErrorInfo: '用户名不存在!'
        }
    }
});

module.exports = router.routes();
